import React, { useRef, useEffect } from 'react';

interface CaptchaProps {
  length?: number;
  width?: number;
  height?: number;
  fontSize?: number;
  onChange?: (code: string) => void;
}

/**
 * 生成随机验证码
 */
const generateCode = (length: number): string => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

/**
 * 绘制验证码到canvas
 */
const drawCaptcha = (
  canvasRef: React.RefObject<HTMLCanvasElement | null>,
  width: number,
  height: number,
  fontSize: number,
  length: number,
  onChange?: (code: string) => void
): void => {
  const canvas = canvasRef.current;
  if (!canvas) return;

  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  // 设置canvas尺寸
  canvas.width = width;
  canvas.height = height;

  // 填充背景色
  ctx.fillStyle = '#f8f8f8';
  ctx.fillRect(0, 0, width, height);

  // 生成随机验证码
  const captchaCode = generateCode(length);
  if (onChange) {
    onChange(captchaCode);
  }

  // 设置文字样式
  ctx.font = `${fontSize}px Arial`;
  ctx.textBaseline = 'middle';

  // 绘制验证码文字
  for (let i = 0; i < captchaCode.length; i++) {
    // 随机颜色
    const r = Math.floor(Math.random() * 80);
    const g = Math.floor(Math.random() * 80);
    const b = Math.floor(Math.random() * 80);
    ctx.fillStyle = `rgb(${r},${g},${b})`;

    // 随机旋转角度
    const angle = (Math.random() - 0.5) * 0.5;
    ctx.save();
    ctx.translate(30 + i * 20, height / 2);
    ctx.rotate(angle);
    ctx.fillText(captchaCode[i], 0, 0);
    ctx.restore();
  }

  // 绘制干扰线
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 100},${Math.random() * 100},${Math.random() * 100})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }

  // 绘制干扰点
  for (let i = 0; i < 40; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 150},${Math.random() * 150},${Math.random() * 150})`;
    ctx.beginPath();
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
};

/**
 * 图形验证码组件
 * 生成随机验证码并绘制到canvas上
 */
const Captcha: React.FC<CaptchaProps> = ({
  length = 4,
  width = 120,
  height = 40,
  fontSize = 24,
  onChange,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  
  // 使用useEffect钩子确保组件挂载后立即绘制验证码，并且在相关属性变化时重新绘制
  useEffect(() => {
    if (canvasRef.current) {
      drawCaptcha(canvasRef, width, height, fontSize, length, onChange);
    }
  }, [fontSize, height, length, onChange, width]);

  // 刷新验证码
  const refreshCaptcha = () => {
    drawCaptcha(canvasRef, width, height, fontSize, length, onChange);
  };

  return (
    <div
      onClick={refreshCaptcha}
      style={{
        cursor: 'pointer',
        padding: 0,
        margin: 0,
        display: 'inline-block',
        height: '32px',
        width: '100px'
      }}
    >
      <canvas ref={canvasRef} style={{ padding: 0, margin: 0 }} />
    </div>
  );
};

export default Captcha;